
// index.js

//ES6模块的 不兼容 需要使用 import
//const exp = require('express'); //require  import

/*************************************
Cannot find package 'express' imported from....
解决: npm install express
*************************************/
//import express from 'express';
const express = require('express')

/* 
express须知：
https://www.runoob.com/nodejs/nodejs-express-framework.html

安装模块
$ c npm install express --save
 
$ c npm install body-parser --save
$ c npm install cookie-parser --save
$ c npm install multer --save
*/
const app = express();
const port = 3000; // 您可以使用任何端口

//import bodyParser from 'body-parser'
const bodyParser = require('body-parser')
//import router from './router'//引用模块 
// parse application/x-www-form-urlencoded
const util = require('util')

const cookie = require('cookie-parser')

//配置模板引擎body-parser一定要在app.use(router)挂载路由之前
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(cookie())

//express.static 中间件来设置静态文件路径 访问如:localhost:3000/res/x.jpg
app.use('/res', express.static('resource'))


app.get('/cookie', (req, res) => {
  console.log("Cookies: " + util.inspect(req.cookies));
  res.send(util.inspect(req.cookies));
});

// 定义一个路由
app.get('/aa', (req, res) => {
  // http://localhost:3000/aa?s=12123&op=59&na=kiou

  const p = req.query
  console.log("get, params:", req.query, p["s"], p["op"], p["na"], p.na)

  res.send('Hello, this is your Express server!');
});

app.post("/po", (req, res) => {
  //需要安装 body-parser 否则req.body无法获取
  const body = req.body
  console.log("post, params", body, body.id, body.name, body.age)

  res.send('post ok!');
})

// 启动服务器 
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

